
<template>
  <div class="risk-content start-exam">
    <div class="exam-title">
      <div class="un-exam">{{ data.ExamName }}</div>
    </div>
    <div class="exam-content">
      <!-- 一 -->
      <div v-for="(val, key) in list" :key="key">
        <div class="mb-10 questions-title">
          <span v-if="key == 0">一、</span>
          <span v-if="key == 1">二、</span>
          <span v-if="key == 2">三、</span>
          <span v-if="key == 3">四、</span>
          <span v-if="key == 4">五、</span>
          {{ val.QName }}共{{ val.children.length }}题（{{
            val.Score + ".0"
          }}分）
        </div>

        <div class="mb-10 exam-questions" v-for="(item, index) in val.children" :key="index">
          <div class="mb-10">
            {{ item.SEQ + 1 }}、{{ item.QName }}（{{ item.Score + ".0分" }}）
          </div>
          <div v-if="item.QType == 1">
            <van-radio-group v-model="item.ItemName">
              <van-radio :name="v.ItemName" class="mb-10" checked-color="#3CB371" v-for="(v, i) in item.Items" :key="i">{{
                v.ItemName }}.{{ v.Item }}</van-radio>
            </van-radio-group>
          </div>
          <div v-if="item.QType == 2">
            <van-checkbox-group v-model="item.ItemName">
              <van-checkbox :name="v2.ItemName" class="mb-10" checked-color="#3CB371" v-for="(v2, i2) in item.Items"
                :key="i2">{{ v2.ItemName }}.{{ v2.Item }}</van-checkbox>
            </van-checkbox-group>
          </div>
          <div v-if="item.QType == 3">
            <van-radio-group v-model="item.ItemName">
              <van-radio :name="v.ItemName" class="mb-10" checked-color="#3CB371" v-for="(v, i) in item.Items" :key="i">{{
                v.ItemName == "A" ? "正确" : v.ItemName == "B" ? "错误" : ""
              }}</van-radio>
            </van-radio-group>
          </div>
          <div v-if="item.QType == 4">
            <van-field v-model="v.ItemName" v-for="(v, i) in item.Items" :key="i" label-width="40" class="input_text"
              :label="i + 1 + '、'" placeholder="请输入答案" />
          </div>
          <div v-if="item.QType == 5">
            <van-field v-model="item.ItemName" label="答案" label-width="40" rows="3" type="textarea" placeholder="请输入答案" />
          </div>
        </div>
      </div>
    </div>
    <div class="exam-btns">
      <div class="exam-btns-l">
        <div class="mb-5">参加考试人：{{ qtbmName }}</div>
        <div v-if="data.ExamMins">剩余时间：{{ text }}</div>
      </div>
      <van-button type="info" @click="_submit()">提交</van-button>
    </div>
  </div>
</template>

<script>
import { getExamPaperQuestionDetail, finishExam } from "@/api/ExExam";
import formatSeconds from "@/utils/formatSeconds.js";
import { mapGetters } from "vuex";
import store from "@/store/index";
import { is_weixin } from "@/utils/common.js";
import { getAxios2 } from "@/utils/request2";
import { temp } from "./temp.js"
export default {
  data() {
    return {
      id: this.$route.query.id,
      industryType: this.$route.query.industryType,
      loading: false,
      data: {},
      text: "",
      list: [],
      FgbmName: localStorage.getItem("FgbmName")
    };
  },
  computed: {
    ...mapGetters(["chnName"]),
  },
  created() {


    this.list = []
    this.getDetail2();

  },
  mounted() {
    if (window.history && window.history.pushState) {
      history.pushState(null, null, document.URL);
      window.addEventListener("popstate", this.goBack, false);
    }
  },
  destroyed() {
    window.removeEventListener("popstate", this.goBack, false);
  },
  methods: {
    async getDetail2() {
      let axios2=await getAxios2()
      // const res = await axios2.post('http://192.168.138.22:8558/app/study/questionList?industryType=00010004')
      const res = await axios2.post('https://hmbm.zatsafety.com/app/study/questionList?industryType='+this.industryType)
      // let res = {}
      // res.data = temp
      res.data.ExamName = "考试名称"
      res.data.ExamType = 1
      res.data.ExamMins = 60
      res.data.IsExamSign = false
      res.data.Attachs = null
      res.data.Questions = []
      res.data.forEach((element, index) => {
        element.QCode = element.questionId
        element.QName = element.questionName,
          element.QType = element.qtype,
          element.Content = null,
          element.Score = element.qscore,
          // element.Answer ="",
          // element.Difficulty=" "2",
          // element.Analysis" "",
          element.SEQ = index
        element.Items = []
        this.pushItem(element.Items, element.optionA, "A", "0")
        this.pushItem(element.Items, element.optionB, "B", "1")
        this.pushItem(element.Items, element.optionC, "C", "2")
        this.pushItem(element.Items, element.optionD, "D", "3")
        res.data.Questions.push(element)
      });
      res.data.Questions.push(
        {
          parentQType: 1,
          QName: "单选题",
          QType: 0,
          Score: 0,
        },
        {
          parentQType: 2,
          QName: "多选题",
          QType: 0,
          Score: 0,
        },
        {
          parentQType: 3,
          QName: "判断题",
          QType: 0,
          Score: 0,
        },
        {
          parentQType: 4,
          QName: "填空题",
          QType: 0,
          Score: 0,
        },
        {
          parentQType: 5,
          QName: "简答题",
          QType: 0,
          Score: 0,
        }
      )
      console.log(res)
      let arryList = this.toTree(res.data.Questions);
      let newArr = arryList.filter(
        (item, index) => item.children != undefined
      );
      // 计算总分
      newArr.forEach((item) => {
        if (item.children) {
          item.children.forEach((item1) => {
            item.Score += item1.Score;
          });
        }
      });
      res.data.ExamMins = parseInt(res.data.ExamMins * 60);
      this.list = newArr;
      this.data = res.data;
      this.time();
    },
    pushItem(list, Acontent, A, index) {
      list.push({
        QCode: Acontent,
        QType: 2,
        Item: Acontent,
        ItemName: A
      })
    },
    goBack() {
      this.$dialog
        .confirm({
          title: "询问",
          message: `您正在考试中，确定要退出吗？`,
        })
        .then(() => {
          // this.$router.replace({ path: '/Train/ExExamExplain?id=' + this.id })
          this.$router.go(-1);
        })
        .catch(() => {
          // on cancel
        });
    },
    toTree(data) {
      var result = [];
      if (!Array.isArray(data)) {
        return result;
      }
      data.forEach((item) => {
        delete item.children;
      });
      let map = {};
      data.forEach((item) => {
        map[item.parentQType] = item;
      });

      data.forEach((item) => {
        let parent = map[item.QType];
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          result.push(item);
        }
      });
      return result;
    },
    // 提交考试
    _submit() {
      const _this = this;
      const newList = this.list.filter((item) => item.children);
      var Details = [];
      var IsExamSign = false;
      newList.filter((item) => {
        item.children.filter((item1) => {
          if (item1.QType == 4) {
            IsExamSign = true;
            let ItemName = [];
            item1.Items.map((v) => {
              if (v.ItemName) {
                ItemName.push(v.ItemName);
              }
            });
            Details.push({
              Answer: Array.isArray(ItemName) ? ItemName.join(",") : ItemName,
              QCode: item1.QCode,
            });
          } else {
            Details.push({
              Answer: Array.isArray(item1.ItemName) ? item1.ItemName.join(",") : item1.ItemName,
              QCode: item1.QCode,
            });
          }
        });
      });
      const data = {
        Details: Details,
        ID: this.data.ID,
        SubjectID: "",
      };
      if (data.Details.every((item) => item.Answer)) {
        this.$dialog
          .confirm({
            title: "询问",
            message: `您确定要提交本次考试吗？`,
          })
          .then(() => {
            this._Calculate(data)
            // this.data.Questions.forEach(element => {

            // if(element.QCode){
            //   let submitDetail=data.Details.find(e=>e.QCode==element.questionId)
            //   element.answer=element.answer.toUpperCase()
            // console.log("提交",submitDetail.Answer)
            // console.log("答案",element.answer)
            // //单选题
            // if(element.QType==1){
            //   if(submitDetail.Answer==element.answer.toUpperCase()){
            //     total_score+=element.Score
            //   }
            // }
            // //多选题
            // else if(element.QType==2){
            //   let scoreTemp=0;
            //   let rightCount=0;
            //   //单个按个的分数
            //   let singleScore=element.Score/element.answer.split('').length
            //   console.log(singleScore)
            //   let AnswerList=submitDetail.Answer.split(",")    
            //   //判断选错
            //   let isError=AnswerList.every(e => element.answer.includes(e));
            //   if(isError){
            //     AnswerList.forEach(e2 => {
            //        if(element.answer.includes(e2)){
            //         rightCount++
            //        }
            //     });
            //     scoreTemp=rightCount*singleScore
            //     console.log("多选得分:"+scoreTemp)
            //     total_score+=scoreTemp
            //   }
            // }
            // }

            // });


          });
      } else {
        this.$dialog
          .confirm({
            title: "询问",
            message: `您还有未做的题目，确认是否提交？`,
          })
          .then(() => {
            this._Calculate(data)
          })
          .catch(() => {
            // on cancel
          });
      }
    },

    _goExam() {
      this.$router.push("/Train/ExExamExplain?id=" + item.ID);
    },
    //计算分数
    _Calculate(data) {
      let total_score = 0;
      let filterDetails = data.Details.filter(es => es.Answer)
      this.data.Questions.forEach(element => {
        if (element.QCode) {
          console.log("submitDetail")
          if (filterDetails.some(e3 => e3.QCode == element.QCode)) {
            let submitDetail = filterDetails.find(e => e.QCode == element.QCode)
            console.log(submitDetail)
            element.answer = element.answer.toUpperCase()
            console.log("提交", submitDetail.Answer)
            console.log("答案", element.answer)
            //单选题
            if (element.QType == 1) {
              if (submitDetail.Answer == element.answer.toUpperCase()) {
                total_score += element.Score
              }
            }
            //多选题
            else if (element.QType == 2) {
              let scoreTemp = 0;
              let rightCount = 0;
              //单个按个的分数
              // let singleScore=element.Score/element.answer.split('').length
              // console.log(singleScore)
              // let AnswerList=submitDetail.Answer.split(",")    
              // //判断选错
              // let isError=AnswerList.every(e => element.answer.includes(e));
              // if(isError){
              //   AnswerList.forEach(e2 => {
              //      if(element.answer.includes(e2)){
              //       rightCount++
              //      }
              //   });
              //   scoreTemp=rightCount*singleScore
              //   console.log("选对个数："+rightCount)
              //   console.log("多选得分:"+scoreTemp)
              //   total_score+=scoreTemp
              // }

              //多选全队才得分
              let submitDetailStr = submitDetail.Answer.replace(/,/g, '')
              if (submitDetailStr == element.answer) {
                total_score += element.Score
              }

            }
          }
        }
      });
   
      this.$dialog
          .confirm({
            title: "询问",
            message: `分数: ` + total_score + "  确认提交？",
          })
          .then(() => {
            this._submitScore(total_score)
          })
          .catch(() => {
            // on cancel
          });

    },
    //提交分数
    async _submitScore(score) {
      let axios2 = await getAxios2()
      let param = {
        fileId: localStorage.getItem('videoPath'),
        userId: localStorage.getItem('userId'),
        isFinish: 1,
        industryType: this.industryType,
        studyTimes: 60.084,
        studyScore: score.toString()
      }
      // const res = await axios2.post('http://192.168.138.22:8558/app/study/saveStudyInfo', param)
      const res = await axios2.post('https://hmbm.zatsafety.com/app/study/saveStudyInfo', param)
      if (res.msg === "success") {
            let wordUrl=res.data.protocol
            localStorage.setItem('data', res.data)
            this.$router.push({path:'/hmbm/showPdfFile',query:{industryType: this.industryType,wordUrl}})
        }
      // const studyData = {
      //   fileId: localStorage.getItem("fileId"),
      //   userId: localStorage.getItem('userId'),
      //   isFinish: 1,
      //   industryType: this.industryType,
      //   studyTimes: localStorage.getItem('currentTime')
      // }
    
    },
    // 倒计时提交
    _submitTime() {
      const _this = this;
      const newList = this.list.filter((item) => item.children);
      var Details = [];
      var IsExamSign = false;
      newList.filter((item) => {
        item.children.filter((item1) => {
          if (item1.QType == 4) {
            IsExamSign = true;
            let ItemName = [];
            item1.Items.map((v) => {
              if (v.ItemName) {
                ItemName.push(v.ItemName);
              }
            });
            Details.push({
              Answer: Array.isArray(ItemName) ? ItemName.join(",") : ItemName,
              QCode: item1.QCode,
            });
          } else {
            Details.push({
              Answer: Array.isArray(item1.ItemName)
                ? item1.ItemName.join(",")
                : item1.ItemName,
              QCode: item1.QCode,
            });
          }
        });
      });
      const data = {
        Details: Details,
        ID: this.data.ID,
        SubjectID: "",
      };
      finishExam(data).then((res) => {
        // if (IsExamSign) {
        // 	_this.$router.push('/Train/ExamSign?id=' + data.ID)
        // } else {
        // 	_this.$router.push('/Train/ExamResult?id=' + data.ID)
        // }
        // _this.$router.push('/Train/ExamResult?id=' + data.ID)
        store.commit("updateResultID", _this.data.ID);
        _this.$router.go(-3);
      });
    },
    // 倒计时
    time() {
      var that = this;
      if (that.data.ExamMins == 0) {
        that.text = "";
      } else {
        that.text = formatSeconds(that.data.ExamMins);
        that.data.ExamMins--;
        setTimeout(function () {
          // console.log(that.data.ExamMins,'that.data.ExamMins');
          // 时间小于1s时，提交
          if (that.data.ExamMins < 1) {
            that._submitTime();
          }
          that.time();
        }, 1000);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.risk-content {
  background-color: #fff;
  min-height: 100vh;
}

.questions-title {
  background-color: #e8f1f8;
  padding: 10px;
}

.exam-title {
  height: 30px;
  background-color: #e8f1f8;
  line-height: 30px;
  padding: 0 10px;
  font-size: 14px;

  .un-exam {
    display: inline-block;
    height: 100%;
    border-bottom: 2px solid #333;
  }
}

.exam-content {
  height: calc(100vh - 60px);
  overflow: hidden;
  overflow-y: auto;
  font-size: 14px;
}

.exam-content::-webkit-scrollbar {
  display: none;
}

.exam-questions {
  padding: 10px;
  border-bottom: 1px solid #eee;

  >div {
    line-height: 1.3;
    font-size: 12px;
  }
}

.exam-btns {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  font-size: 14px;
  background-color: #fff;
  border-top: 1px solid #ccc;

  .exam-btns-l {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 50px;
    padding-left: 10px;
    font-size: 12px;
  }

  .van-button {
    width: 25%;
    height: 50px;
    border-radius: 0;
  }
}
</style>
<style lang="less">
.start-exam {
  .van-field__control {
    background-color: #f8f8f8 !important;
  }
}
</style>